const express = require('express');

const app = express();
const fs = require('fs');
//获取客户端 ip 地址
function getClientIp(req) {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress;
}
app.use(function(request, response, next){
    response.setHeader('Access-Control-Allow-Origin', "*");
    response.setHeader('Access-Control-Allow-Headers', "*");
    fs.writeFileSync('./access.log', getClientIp(request) + '---' +decodeURI(request.url) + '\r\n', {flag: 'a'});
    next();
});

app.all('/server', (request, response) => {
    response.send('HELLO abc');
});

app.all('/json-server', (request, response) => {
    //响应结果 JSON 格式的响应体
    let data = {
        errno: 1,
        errmsg: '此用户名已经存在'
    };
    //将 js 对象转化为 JSON 字符串
    let json = JSON.stringify(data);
    //设置响应头 类型与字符集
    response.setHeader('Content-Type','application/json; charset=utf-8');
    //响应结果
    response.end(json);
});

//创建一个延时响应的路由规则
app.all('/delay-server', (request, response) => {
    setTimeout(() => {
        response.send('元宵节快乐!!!');
    }, 4000);
}); 

//为 jsonp 请求添加路由规则
app.get('/jsonp-server', (request, response) => {
    let data = '此用户名已经存在';
    //获取请求中 cb 参数
    let cb = request.query.cb;
    response.end(`${cb}("${data}")`);// handle("此用户名已经存在")
});



app.all('/jquery-server', (request, response) => {
    // response.send('HELLO jQuery AJAX!!!');
    response.end('{"id":2021, "keywords":"ABC"}');
}); 


app.listen(80, () => {
    console.log('服务已经启动....');
})
